package com.mirror.tk.core.module.sys.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Maps;
import com.mirror.tk.core.module.sys.dao.SysAttachmentDao;
import com.mirror.tk.core.module.sys.domain.SysAttachment;
import com.mirror.tk.core.module.sys.service.SysAttachmentService;
import com.mirror.tk.framework.common.service.EntityServiceImpl;

@Service("sysAttachmentService")
public class SysAttachmentServiceImpl extends EntityServiceImpl<SysAttachment, SysAttachmentDao> implements SysAttachmentService {

	@Value("${attachment.root}")
	private String attachRoot;

	public SysAttachment getAttachment(Long userId, String attachUrl) {
		Map<String, Object> map = Maps.newHashMap();
		map.put("EQ_attachUrl", attachUrl);
		if(null != userId){
			map.put("EQ_userId", userId);
		}
		List<SysAttachment> list = query(map, null);
		if(null != list && list.size() > 0) 
			return list.get(0);
		return null;
	}
	
	@Override
	public SysAttachment delete(Long userId, String oldAttachUrl) {
		SysAttachment attachment = getAttachment(userId, oldAttachUrl);
		if (attachment == null) {
			return null;
		}
		File file = new File(attachment.getFilePath());
		if (file.exists() && file.isFile()) {
			final String fileName = file.getName().substring(0, file.getName().lastIndexOf("."));
			File[] files = file.getParentFile().listFiles(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					return name.indexOf(fileName) != -1;
				}
			});
			for (File f : files) {
				f.delete();
			}
		}
		removeById(attachment.getId());
		return attachment;
	}

	@Override
	public SysAttachment delete(String oldAttachUrl) {
		return delete(null, oldAttachUrl);
	}

	@Override
	public SysAttachment upload(Long userId, String sysKey, String relationKey, MultipartFile file) {
		SysAttachment attachment = new SysAttachment();
		attachment.setUserId(userId);
		attachment.setRelationKey(relationKey);
		attachment.setSourceName(file.getOriginalFilename());
		attachment.setFileType(file.getContentType());
		attachment.setFileSize(file.getSize());
		// 文件名
		String fileName = UUID.randomUUID().toString().replaceAll("-", "");
		// 文件后缀
		String suffix = "";
		int len = file.getOriginalFilename().lastIndexOf(".");
		if (len >= 1) {
			suffix = file.getOriginalFilename().substring(len);
		}
		attachment.setFileName(fileName + suffix);
		// 组装保存路径-文件夹（按照关联模块区分）
		Calendar calendar = Calendar.getInstance();
		String path = String.format("/attach/%s/%s/%s/%s/%s", 
				relationKey,
				calendar.get(Calendar.YEAR), 
				calendar.get(Calendar.MONTH) + 1,
				calendar.get(Calendar.DATE), 
				attachment.getFileName());
		// 原始文件保存位置
		attachment.setFilePath(attachRoot + path);
		// 站点下的访问路径
		attachment.setAttachUrl(path);
		attachment.setCreateTime(new Date());
		File fileRoot = new File(attachment.getFilePath());

		if (fileRoot.getParentFile().isDirectory() || fileRoot.getParentFile().mkdirs()) {
			FileOutputStream fileOutputStream = null;
			try {
				fileOutputStream = new FileOutputStream(fileRoot);
				fileOutputStream.write(file.getBytes());
			} catch (Exception ex) {
				throw new RuntimeException(ex);
			} finally {
				if (fileOutputStream != null) {
					try {
						fileOutputStream.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		save(attachment);
		return attachment;
	}

	@Override
	public SysAttachment upload(Long userId, String sysKey, String relationKey, MultipartFile file, String oldAttachUrl) {
		if (StringUtils.isNotBlank(oldAttachUrl)) {
			delete(oldAttachUrl);
		}
		try {
			return upload(userId, sysKey, relationKey, file);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
